const app = getApp()
// 语言
var util = require('../../utils/util.js')
import event from '../../utils/event'
Page({
  data: {
    balance:0,
    freeze:0,
    score:0,
    score_sign_continuous:0,
    //语言 - begin
    language: '',
    //语言 - end
    tabClass: ["", "", "", "", ""],
    logged:true,
    login:0
  },
  // 语言
  // 设置language变量（翻译Object）
  setLanguage() {
    var lang = wx.T.getLanguage()
    this.setData({
      language: lang,
      selectSize: lang.select_attribute
    });
  },
  changeLanguage() {
    var lang = wx.T.getLanguage()
    this.setData({
      language: lang,
      selectSize: lang.select_attribute
    });
  },
  //加入会员
  joinMember: function(){
    wx.navigateTo({
      url: '/pages/joinMember/joinMember',
    })
  },
  onLoad: function () {
    var that = this;
    // 语言
    // 设置当前页面的language变量 - 每个页面都要有
    this.setLanguage();
    event.on("languageChanged", this, this.changeLanguage); // (2)
    // 设置当前页面的language Index - 每个页面都要有
    wx.T.setLocaleByIndex(wx.T.langIndex);
    console.log()
    this.getSaleData();
  },
  // 获取销售数据
  getSaleData(){
    var that=this;
    wx.request({
      url: app.globalData.urls + '/manage/today-data',
      header: app.getRequestHeader(),
      data: {
        bdmin_user_id:util.getBdmin_user_id()
      },
      success: function (res) {
        let result = res.data.data;
        that.setData({
          saleData:result
        })
      }
    });
  },
  getNumber(){
    var that=this;
    wx.request({
      url: app.globalData.urls + '/index/data-num',
      header: app.getRequestHeader(),
      data: {},
      success: function (res) {
        let result = res.data.data;
        that.setData(result)
      }
    });
  },
  wxLogin: function(jumpLogin){
    var that = this;
    wx.login({
      success: function (res) {
        that.setData({
          code:res.code
        })
        wx.request({
          url: app.globalData.urls + "/customer/login/wxcode",  // "/user/wxapp/login",
          header: app.getPostRequestHeader(),
          method: 'POST',
          data: {
            code: res.code,
            bdmin_user_id:util.share_bdmin_user_id()
          },
          success: function (res) {
            if(res.data.code==200){
              that.setData({
                session_key:res.data.data.session_key
              })
            }
            that.loginAccount(jumpLogin);
            app.saveReponseHeader(res);

          }
        });
      }
    });
  },
  loginAccount: function (jumpLogin) {
    var that = this;
    // wx.showLoading({
    //   title: that.data.language.load_user_information,
    // })
    wx.request({
      url: app.globalData.urls + '/customer/login/wxindex',
      header: app.getRequestHeader(),
      data: {
        bdmin_user_id:util.share_bdmin_user_id()
      },
      success: function (res) {
        // 如果已经登陆，则跳转page/my/my
        if (res.data.code != '1100006') {
          that.setData({
            logged: false
          })

          that.wxLogin();

        }else{
          let getData = res.data.data;
          let login  = wx.getStorageSync('isLogin')
          console.log("--测试用户登录-",getData,login,getData.head_url==""|| getData.phone=="")
          if ((getData.head_url==""|| getData.phone=="" || !getData.phone || !getData.head_url) && login!=1)  {

            wx.navigateTo({
              url: "/pages/login/login"
            })
          }else{
            if(res.data.data.head_url==""){
              util.getUserInfo(app,res.data.data);
            }
            let result = res.data.data;
            that.setData({
              logged: true,
              userinfo:result,
              is_merchant:res.data.data.is_merchant
            })
            wx.setStorage({
              data: result,
              key: 'customer_id',
            })

            if(!result.phone)that.recodePhone(result);

            app.globalData.userInfo = {
              nickName: result.firstname,
              avatarUrl: result.head_url,
              customer_id: result.customer_id
            }
            var value = wx.getStorageSync('userInfo')
            if (value==""){
              wx.setStorage({
                key: "userInfo",
                data: {
                  nickName: result.firstname,
                  avatarUrl: result.head_url,
                  customer_id: result.customer_id
                }
              })
            }
            wx.getStorage({
              key: 'userInfo',
              success(res) {
                app.globalData.userInfo = res.data
              }
            })


            wx.hideLoading();
            app.saveReponseHeader(res);

          }


        }
      }
    });
  },
  onReady(){
    // 发起登录验证
    // this.loginAccount(true)
  },
  onShow() {
    this.loginAccount(false)
    // 数字
    this.getNumber();
    // 添加店铺浏览记录
    util.storeBrower(app)
  },
  getUserApiInfo: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/user/detail',
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            apiUserInfoMap: res.data.data
          });
        }
      }
    })
  },
  getUserAmount: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/user/amount',
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            balance: res.data.data.balance,
            freeze: res.data.data.freeze,
            score: res.data.data.score
          });
        }
      }
    })
  },
  getInfo: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/config/get-value',
      data: {
        key: "mallinfo"
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            getInfo: res.data.data.value
          });
        }
      }
    })
  },
  checkScoreSign: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/score/today-signed',
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            score_sign_continuous: res.data.data.continuous
          });
        }
      }
    })
  },
  // 记录用户手机号
  recodePhone(data){
    var that=this;
    if(data.length==0) return;
    let getPhone = wx.getStorageSync('phone');
    if(!getPhone.iv ) return;
    // wx.request({
    //   url: app.globalData.urls + "/order/get-session-key",
    //   header: app.getPostRequestHeader(),
    //   method: 'POST',
    //   data: {
    //     code:that.data.code
    //   },
    //   success: function (res) {
    //     console.log("新街口",res.data)
    //     if(res.data.code==200){
    // 获取手机号信息
    wx.request({
      url: app.globalData.urls + "/order/update-phone",
      header: app.getPostRequestHeader(),
      method: 'POST',
      data: {
        session_key:that.data.session_key,
        customer_id:data.customer_id,
        encryptedData:getPhone.encryptedData,
        iv:getPhone.iv
      },
      success: function (res) {
        let login  = wx.getStorageSync('isLogin');
        if(res.data.code!=200 && login!=1){
          wx.navigateTo({
            url: "/pages/login/login"
          })
        }
      }
    });


  },

  scoresign: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/score/sign',
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.getUserAmount();
          that.checkScoreSign();
        } else {
          wx.showModal({
            title: '错误',
            content: res.data.msg,
            showCancel: false
          })
        }
      }
    })
  },
  relogin:function(){
    var that = this;
    wx.authorize({
      scope: 'scope.userInfo',
      success() {
        app.globalData.token = null;
        app.login();
        wx.showModal({
          title: '提示',
          content: '重新登陆成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              that.onShow();
            }
          }
        })
      },
      fail(res){
        //console.log(res);
        wx.openSetting({});
      }
    })
  },
})
